#include "main_widget.h"
#include "ui_main_widget.h"
#include <QtCore/QDateTime>
#include <QtMqtt/QMqttClient>
#include <QtWidgets/QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>
#include <QThread>


main_widget::main_widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::main_widget)
{
    ui->setupUi(this);

    // 创建 MQTT 客户端对象并设置主机和端口
    m_client = new QMqttClient(this);
    m_client->setHostname("192.168.137.1");  // 设置 MQTT 服务器的 IP 地址
    m_client->setPort(1883);  // 设置 MQTT 服务器的端口号



    // 订阅主题

    connect(m_client, &QMqttClient::messageReceived, this, [this](const QByteArray &message, const QMqttTopicName &topic) {
        // 获取当前时间戳并构造接收到消息的日志内容
        const QString content = QDateTime::currentDateTime().toString()
                                + QLatin1String(" Received Topic: ")
                                + topic.name()     // 获取消息主题名
                                + QLatin1String(" Message: ")
                                + QString(message)  // 将QByteArray转换为QString
                                + QLatin1Char('\n'); // 添加换行符

       // QString fileName = QFileDialog::getOpenFileName(this, "选择文件", "", "文本文件 (*.txt);;所有文件 (*.*)");

        QString fileName("data.log");
         if (!fileName.isEmpty()) {
                QFile file(fileName);

                // 打开文件以读取并写入内容
                if (file.open(QIODevice::ReadWrite | QIODevice::Text)) {
                    // 读取文件内容并显示
                    QTextStream in(&file);
                    QString fileContent = in.readAll();
                    //fileLabel->setText(fileContent);

                    // 写入新内容到文件末尾
                    QTextStream out(&file);
                    file.seek(file.size()); // 移动到文件末尾
                    out << content;

                  //  QMessageBox::information(this, "成功", "文件已更新成功！");
                    file.close();
                } else {
                   // QMessageBox::warning(this, "错误", "无法打开文件");
                }

         }
         QJsonDocument doc = QJsonDocument::fromJson(message);

        // 检查是否解析成功
        if (doc.isObject()) {
            // 获取 JSON 对象
            QJsonObject obj = doc.object();

            // 获取各个字段
            int temp = obj["temp"].toInt();
            int humi = obj["humi"].toInt();
            int light = obj["light"].toInt();
            int V = obj["V"].toInt();

            int temp_MIN = obj["temp_MIN"].toInt();
            int temp_MAX =   obj["temp_MAX"].toInt();

            int himu_MIN = obj["himu_MIN"].toInt();
            int himu_MAX = obj["himu_MAX"].toInt();


            int V_MAX = obj["V_MAX"].toInt();
            int V_MIN = obj["V_MIN"].toInt();

            int light_MAX = obj["light_MAX"].toInt();
            int light_MIN = obj["light_MIN"].toInt();

            int FAN = obj["FAN"].toInt();

            int LED = obj["LED"].toInt();
            int BEEP = obj["BEEP"].toInt();


            ui->label_temp->setText(QString("%1  °C").arg(temp ));
            ui->label_humi->setText(QString("%1 %").arg(humi));
            ui->label_light->setText(QString("%1  ").arg(light));
            ui->label_V->setText(QString("%1 mV").arg(V));


            ui->label_temp_2->setText(QString("设定范围: %1 - %2 °C").arg(temp_MIN).arg(temp_MAX));
            ui->label_humi_2->setText(QString("设定范围:%1 - %2 %").arg(himu_MIN).arg(himu_MAX));
            ui->label_light_2->setText(QString("设定范围:%1 - %2%").arg(light_MIN).arg(light_MAX));
            ui->label_V_2->setText(QString("设定范围:%1 - %2 mV").arg(V_MIN).arg(V_MAX));

            ui->label_LED_2->setText(QString("%1 ").arg(102-LED ));
            ui->label_FAN_2->setText(QString("%1").arg(102 -FAN));
            ui->label_BEEP_2->setText(QString("%1").arg(BEEP));



            qDebug() << "FAN:" << FAN;
            qDebug() << "LED:" << LED;
            qDebug() << "BEEP:" << BEEP;
            // 打印输出解析结果
            qDebug() << "Temperature:" << temp;
            qDebug() << "Humidity:" << humi;
            qDebug() << "Light:" << light;
            qDebug() << "V:" << V;
        } else {
            qDebug() << "Invalid JSON data!";
        }
        // 将内容插入到文本框中
        ui->editLog->insertPlainText(content);
    });

    connect(m_client, &QMqttClient::pingResponseReceived, this, [this]() {
        const QString content = QDateTime::currentDateTime().toString()
        + QLatin1String(" PingResponse")
            + QLatin1Char('\n');
        ui->editLog->insertPlainText(content);
    });
        ui->label_BEEP_value->setText(QString("0"));
        ui->label_LED_value->setText(QString("0"));
        ui->label_FAN_value->setText(QString("0"));



    // 建立与 MQTT 服务器的连接
    m_client->connectToHost();
/*   connect(ui->dial_LED, &QDial::valueChanged, this, [=](int value) {
        qDebug() << "Dial value changed to:" << value;
        label->setText(QString("Value: %1").arg(value));
    });
*/

}

main_widget::~main_widget()
{
    delete ui;
}

void main_widget::mqttset(QString temp_str , int mqtt_temp)
{

        QJsonObject jsonObj;
        jsonObj[temp_str] = mqtt_temp;
        // 创建一个QJsonDocument并转换为QByteArray
        QJsonDocument jsonDoc(jsonObj);
        // 要发送的消息
        QByteArray max_message =jsonDoc.toJson();
        // 创建 MQTT 主题
        QMqttTopicName topic("/SET");

        // 发布消息到 /SET 主题
        if (m_client->publish(topic, max_message) == -1) {
            QMessageBox::critical(this, "Error", "Failed to publish message.");
        }/**/

}







void main_widget::on_pushButton_clicked()
{   ui->label_LED_value->setText(0);
    QJsonObject jsonObj;
    jsonObj["LED"] = 102;

    // 创建一个QJsonDocument并转换为QByteArray
    QJsonDocument jsonDoc(jsonObj);
    // 要发送的消息
    QByteArray message =jsonDoc.toJson();

    // 创建 MQTT 主题
    QMqttTopicName topic("/SET");

    // 发布消息到 /SET 主题
    if (m_client->publish(topic, message) == -1) {
        QMessageBox::critical(this, "Error", "Failed to publish message.");
    }/**/
}


void main_widget::on_pushButton_2_clicked()
{
    QJsonObject jsonObj;
    jsonObj["FAN"] = 102;
    ui->label_FAN_value->setText(0);
    // 创建一个QJsonDocument并转换为QByteArray
    QJsonDocument jsonDoc(jsonObj);
    // 要发送的消息
    QByteArray message =jsonDoc.toJson();

    // 创建 MQTT 主题
    QMqttTopicName topic("/SET");

    // 发布消息到 /SET 主题
    if (m_client->publish(topic, message) == -1) {
        QMessageBox::critical(this, "Error", "Failed to publish message.");
    }/**/
}


void main_widget::on_pushButton_3_clicked()
{
    ui->label_BEEP_value->setText(0);
    QJsonObject jsonObj;
    jsonObj["BEEP"] = 0;

    // 创建一个QJsonDocument并转换为QByteArray
    QJsonDocument jsonDoc(jsonObj);
    // 要发送的消息
    QByteArray message =jsonDoc.toJson();

    // 创建 MQTT 主题
    QMqttTopicName topic("/SET");

    // 发布消息到 /SET 主题
    if (m_client->publish(topic, message) == -1) {
        QMessageBox::critical(this, "Error", "Failed to publish message.");
    }/**/
}


void main_widget::on_pushButton_4_clicked()
{

    double min_temp = ui->doubleSpinBox_temp_min->value();
    qDebug() << "Min temperature: " << min_temp;
    double max_temp = ui->doubleSpinBox_temp_max->value();
    qDebug() << "Max temperature: " << max_temp;
    if (min_temp  >=  max_temp) {
        QMessageBox::warning(this, "警告","请输入正确的数值！");
        return;
    }else
    {
        QJsonObject jsonObj;
        jsonObj["Temp_Min"] = min_temp;
        // 创建一个QJsonDocument并转换为QByteArray
        QJsonDocument jsonDoc(jsonObj);
        // 要发送的消息
        QByteArray min_message =jsonDoc.toJson();
        // 创建 MQTT 主题
        QMqttTopicName topic("/SET");

        // 发布消息到 /SET 主题
        if (m_client->publish(topic, min_message) == -1) {
            QMessageBox::critical(this, "Error", "Failed to publish message.");
        }/**/

    }

}


void main_widget::on_pushButton_5_clicked()
{
    QMqttTopicFilter topicFilter("/POST");
    m_client->connectToHost();
    // 确保连接成功后再订阅
    if (m_client->state() == QMqttClient::Connected) {
        auto subscription = m_client->subscribe(topicFilter);

        if (!subscription) {
            QMessageBox::critical(this,"错误","无法订阅,请确定是否连接成功!");
            return;
        }
             QMessageBox::information(this, "成功", "自动更新数据获取成功!");

    } else {

        QMessageBox::critical(this,"错误", "连接失败，请检查互联网连接! ");

    }


}


void main_widget::on_dial_LED_valueChanged(int value)
{
    qDebug() << "Dial value changed to:" << value;
    ui->label_LED_value->setText(QString(" %1 ").arg((102- value)));
    // 创建一个QJsonObject
    QJsonObject jsonObj;
    jsonObj["LED"] = value;

    // 创建一个QJsonDocument并转换为QByteArray
    QJsonDocument jsonDoc(jsonObj);
    // 要发送的消息
    QByteArray message =jsonDoc.toJson();

    // 创建 MQTT 主题
    QMqttTopicName topic("/SET");

    // 发布消息到 /SET 主题
    if (m_client->publish(topic, message) == -1) {
        QMessageBox::critical(this, "Error", "Failed to publish message.");
    }/**/
}


void main_widget::on_dial_FAN_valueChanged(int value)
{
    qDebug() << "Dial value changed to:" << value;
    ui->label_FAN_value->setText(QString(" %1 ").arg((102- value)));
    // 创建一个QJsonObject
    QJsonObject jsonObj;
    jsonObj["FAN"] = value;

    // 创建一个QJsonDocument并转换为QByteArray
    QJsonDocument jsonDoc(jsonObj);
    // 要发送的消息
    QByteArray message =jsonDoc.toJson();

    // 创建 MQTT 主题
    QMqttTopicName topic("/SET");

    // 发布消息到 /SET 主题
    if (m_client->publish(topic, message) == -1) {
        QMessageBox::critical(this, "Error", "Failed to publish message.");
    }/**/



}


void main_widget::on_dial_BEEP_valueChanged(int value)
{
    qDebug() << "Dial value changed to:" << value;
    ui->label_BEEP_value->setText(QString(" %1 ").arg(value));
    // 创建一个QJsonObject
    QJsonObject jsonObj;
    jsonObj["BEEP"] = value;
    // 创建一个QJsonDocument并转换为QByteArray
    QJsonDocument jsonDoc(jsonObj);
    // 要发送的消息
    QByteArray message =jsonDoc.toJson();

    // 创建 MQTT 主题
    QMqttTopicName topic("/SET");

    // 发布消息到 /SET 主题
    if (m_client->publish(topic, message) == -1) {
        QMessageBox::critical(this, "Error", "Failed to publish message.");
    }/**/
}

void main_widget::on_pushButton_6_clicked()
{
    // 假设你在某个函数中需要读取 doubleSpinBox_temp_min 的值

    double min_temp = ui->doubleSpinBox_humi_min ->value();
    qDebug() << "Min temperature: " << min_temp;
    double max_temp = ui->doubleSpinBox_humi_max->value();
    qDebug() << "Max temperature: " << max_temp;
    if (min_temp  >=  max_temp) {
        QMessageBox::warning(this, "警告","请输入正确的数值！");
        return;
    }else
    {
        QJsonObject jsonObj;
        jsonObj["Humid_Min"] = min_temp;
        // 创建一个QJsonDocument并转换为QByteArray
        QJsonDocument jsonDoc(jsonObj);
        // 要发送的消息
        QByteArray max_message =jsonDoc.toJson();
        // 创建 MQTT 主题
        QMqttTopicName topic("/SET");

        // 发布消息到 /SET 主题
        if (m_client->publish(topic, max_message) == -1) {
            QMessageBox::critical(this, "Error", "Failed to publish message.");
        }/**/

    }



}


void main_widget::on_pushButton_7_clicked()
{

    double min_temp = ui->doubleSpinBox_temp_min->value();
    qDebug() << "Min temperature: " << min_temp;
    double max_temp = ui->doubleSpinBox_temp_max->value();
    qDebug() << "Max temperature: " << max_temp;
    if (min_temp  >=  max_temp) {
        QMessageBox::warning(this, "警告","请输入正确的数值！");
        return;
    }else
    {
        QJsonObject jsonObj;
        jsonObj["Temp_Max"] = max_temp;
        // 创建一个QJsonDocument并转换为QByteArray
        QJsonDocument jsonDoc(jsonObj);
        // 要发送的消息
        QByteArray max_message =jsonDoc.toJson();
        // 创建 MQTT 主题
        QMqttTopicName topic("/SET");

        // 发布消息到 /SET 主题
        if (m_client->publish(topic, max_message) == -1) {
            QMessageBox::critical(this, "Error", "Failed to publish message.");
        }/**/

    }
}


void main_widget::on_checkBox_checkStateChanged(const Qt::CheckState &arg1)
{







}


void main_widget::on_checkBox_stateChanged(int arg1)
{

        QJsonObject jsonObj;
        jsonObj["AUTO"] = arg1;
        // 创建一个QJsonDocument并转换为QByteArray
        QJsonDocument jsonDoc(jsonObj);
        // 要发送的消息
        QByteArray max_message =jsonDoc.toJson();
        // 创建 MQTT 主题
        QMqttTopicName topic("/SET");

        // 发布消息到 /SET 主题
        if (m_client->publish(topic, max_message) == -1) {
            QMessageBox::critical(this, "Error", "Failed to publish message.");
        }/**/

}


void main_widget::on_pushButton_12_clicked()
{
    double min_temp = ui->doubleSpinBox_humi_min->value();
    qDebug() << "Min temperature: " << min_temp;
    double max_temp = ui->doubleSpinBox_humi_max->value();
    qDebug() << "Max temperature: " << max_temp;
    if (min_temp  >=  max_temp) {
        QMessageBox::warning(this, "警告","请输入正确的数值！");
        return;
    }else
    {
        QJsonObject jsonObj;
        jsonObj["Humid_Max"] = max_temp;
        // 创建一个QJsonDocument并转换为QByteArray
        QJsonDocument jsonDoc(jsonObj);
        // 要发送的消息
        QByteArray max_message =jsonDoc.toJson();
        // 创建 MQTT 主题
        QMqttTopicName topic("/SET");

        // 发布消息到 /SET 主题
        if (m_client->publish(topic, max_message) == -1) {
            QMessageBox::critical(this, "Error", "Failed to publish message.");
        }/**/

    }
}


void main_widget::on_pushButton_11_clicked()
{
    double min_temp = ui->doubleSpinBox_light_min->value();
    qDebug() << "Min temperature: " << min_temp;
    double max_temp = ui->doubleSpinBox_light_max->value();
    qDebug() << "Max temperature: " << max_temp;
    if (min_temp  >=  max_temp) {
        QMessageBox::warning(this, "警告","请输入正确的数值！");
        return;
    }else
    {
        QJsonObject jsonObj;
        jsonObj["Lgt_Min"] = min_temp;
        // 创建一个QJsonDocument并转换为QByteArray
        QJsonDocument jsonDoc(jsonObj);
        // 要发送的消息
        QByteArray max_message =jsonDoc.toJson();
        // 创建 MQTT 主题
        QMqttTopicName topic("/SET");

        // 发布消息到 /SET 主题
        if (m_client->publish(topic, max_message) == -1) {
            QMessageBox::critical(this, "Error", "Failed to publish message.");
        }/**/

    }
}


void main_widget::on_pushButton_13_clicked()
{
    double min_temp = ui->doubleSpinBox_light_min->value();
    qDebug() << "Min temperature: " << min_temp;
    double max_temp = ui->doubleSpinBox_light_max->value();
    qDebug() << "Max temperature: " << max_temp;
    if (min_temp  >=  max_temp) {
        QMessageBox::warning(this, "警告","请输入正确的数值！");
        return;
    }else
    {
        QJsonObject jsonObj;
        jsonObj["Lgt_Max"] = max_temp;
        // 创建一个QJsonDocument并转换为QByteArray
        QJsonDocument jsonDoc(jsonObj);
        // 要发送的消息
        QByteArray max_message =jsonDoc.toJson();
        // 创建 MQTT 主题
        QMqttTopicName topic("/SET");

        // 发布消息到 /SET 主题
        if (m_client->publish(topic, max_message) == -1) {
            QMessageBox::critical(this, "Error", "Failed to publish message.");
        }/**/

    }
}


void main_widget::on_pushButton_14_clicked()
{
    double min_temp = ui->doubleSpinBox_v_min->value();
    qDebug() << "Min temperature: " << min_temp;
    double max_temp = ui->doubleSpinBox_v_max->value();
    qDebug() << "Max temperature: " << max_temp;
    if (min_temp  >=  max_temp) {
        QMessageBox::warning(this, "警告","请输入正确的数值！");
        return;
    }else
    {
        QJsonObject jsonObj;
        jsonObj["Pot_Min"] = min_temp;
        // 创建一个QJsonDocument并转换为QByteArray
        QJsonDocument jsonDoc(jsonObj);
        // 要发送的消息
        QByteArray min_message =jsonDoc.toJson();
        // 创建 MQTT 主题
        QMqttTopicName topic("/SET");

        // 发布消息到 /SET 主题
        if (m_client->publish(topic, min_message) == -1) {
            QMessageBox::critical(this, "Error", "Failed to publish message.");
        }/**/

    }
}


void main_widget::on_pushButton_15_clicked()
{
    double min_temp = ui->doubleSpinBox_v_min->value();
    qDebug() << "Min temperature: " << min_temp;
    double max_temp = ui->doubleSpinBox_v_max->value();
    qDebug() << "Max temperature: " << max_temp;
    if (min_temp  >=  max_temp) {
        QMessageBox::warning(this, "警告","请输入正确的数值！");
        return;
    }else
    {
        QJsonObject jsonObj;
        jsonObj["Pot_Max"] = max_temp;
        // 创建一个QJsonDocument并转换为QByteArray
        QJsonDocument jsonDoc(jsonObj);
        // 要发送的消息
        QByteArray max_message =jsonDoc.toJson();
        // 创建 MQTT 主题
        QMqttTopicName topic("/SET");

        // 发布消息到 /SET 主题
        if (m_client->publish(topic, max_message) == -1) {
            QMessageBox::critical(this, "Error", "Failed to publish message.");
        }/**/

    }
}

